home *** CD-ROM | disk | FTP | other *** search
- Path: grimsel.zurich.ibm.com!usenet
- From: wgk@zurich.ibm.com (Keith Whittingham)
- Newsgroups: comp.lang.c++
- Subject: Re: Arrays or Pointers?
- Date: 9 Apr 1996 09:33:45 GMT
- Organization: IBM Research, ZRH
- Message-ID: <4kdatp$kcp@grimsel.zurich.ibm.com>
- References: <4kbsk3$f07@zeus.tcp.co.uk>
- Reply-To: wgk@zurich.ibm.com
- NNTP-Posting-Host: pine.zurich.ibm.com
- X-Newsreader: IBM NewsReader/2 v1.00
-
- In <4kbsk3$f07@zeus.tcp.co.uk>, daveg@tcp.co.uk (David) writes:
- >I'm currently on a C++ course and we seem to be using pointers a fair
- >bit. On questioning this, was told that pointers where quicker than
- >using arrays. In which situations should I be using arrays over
- >pointers and vice versa?
- >
-
- It's a real shame there's not more C/C++ programmers who understand
- the code produced by the compiler in order to implement the code.
- You need only a simplistic understanding of assembler and a bit
- of curiosity - understanding it also makes it very easy to
- clear up bugs like:
-
- if(x = y);
- puts(x)
-
- etc.
-
- Anyway, I digress. There is no reason why pointers should be faster
- or slower than arrays. Multi dimensioned arrays tend to be slower
- because of the way a program might access them only. Take for
- example a 25 x 80 character screen. Using array:
-
- char Screen[25][80];
- int r = 2;
- int c = 0;
-
- Screen[r][c++] = 'A';
- Screen[r][c++] = 'B';
- Screen[r][c++] = 'C';
-
- p = &Screen[2][0];
- *p++ = 'A';
- *p++ = 'B';
- *p = 'C';
-
- and using pointers...
-
- char Screen[25*80];
- char *p;
-
- p = &Screen[2*80];
- *p++ = 'A';
- *p++ = 'B';
- *p = 'C';
-
- I'm not saying either of the above is how it should be done but I
- am suggesting that if you looked of the shoulder of Mr AverageProgrammer
- that's what you might find. Now expand with the assembler...
-
- Arrays...
-
- int r = 2;
- int c = 0;
- mov cx,0002
- xor dx,dx
-
- Screen[r][c++] = 'A';
- mov bx,cx
- imul bx,0050
- add bx,dx
- mov byte ptr [bx+02A0],41
- inc dx
- Screen[r][c++] = 'B';
- mov bx,cx
- imul bx,0050
- add bx,dx
- mov byte ptr [bx+02A0],42
- inc dx
- Screen[r][c++] = 'C';
- mov bx,cx
- imul bx,0050
- add bx,dx
- mov byte ptr [bx+02A0],43
- inc dx
-
-
- Pointers...
-
- p = &Screen[2*80];
- mov si,0340
- *p++ = 'A';
- mov byte ptr [si],41
- inc si
- *p++ = 'B';
- mov byte ptr [si],42
- inc si
- *p = 'C';
- mov byte ptr [si],43
-
- The mutiplication instruction (imul in this case) tends to be quite
- thirsty and one imul could burn as many clock cycles as all 6 lines
- of assembler in the pointers example.
-
- After seeing the above example you'll probably make the correct
- choice yourself...
-
- Keith
-
-
-